package pinyin

import (
	"encoding/hex"
	"errors"
	"fmt"

	"github.com/Tang-RoseChild/mahonia"
)

func ChineseToPinyin(schinese string) (string, error) {
	return GoChineseToPinyin(schinese, true)
}

func GoChineseToPinyin(schinese string, full bool) (string, error) {
	enc := mahonia.NewEncoder("GBK")
	str := enc.ConvertString(schinese)

	var retstr string

	//先把str转换为二进制
	strhex := hex.EncodeToString([]byte(str))

	for index := 0; index <= len(strhex)-2; {
		var sleft, sright string
		sleft = strhex[index : index+2]
		if index+4 <= len(strhex) {
			sright = strhex[index+2 : index+4]
		} else {
			sright = ""
		}

		bleft, err := hex.DecodeString(sleft)
		if err != nil {
			return "", errors.New("hex转换错误:" + err.Error())
		}
		bright, err := hex.DecodeString(sright)
		if err != nil {
			return "", errors.New("hex转换错误:" + err.Error())
		}

		ileft := int(bleft[0])
		var iright int
		if len(bright) > 0 {
			iright = int(bright[0])
		} else {
			iright = 0
		}

		var mycode int
		if ileft > 128 {
			index = index + 4
			mycode = 65536 - ileft*256 - iright
			for {

				if mycode > 25358 {
					fmt.Printf("%d\n", mycode)
					retstr = retstr + "a"
					break
				}

				if str, ok := CRT[mycode]; ok {
					if full {
						retstr = retstr + str
					} else {
						retstr = retstr + string(str[0])
					}

					break
				}
				mycode = mycode + 1
			}

		} else {
			if full {
				retstr = retstr + string([]byte{byte(ileft)})
			} else {
				retstr = retstr + string([]byte{byte(ileft)}[0])
			}
			index = index + 2
		}

	}

	return retstr, nil
}
